package com.libui.webview.jsinterface.handlers

import com.libbase.cast
import com.libui.webview.WebViewEx
import com.libui.webview.jsinterface.WebViewHandlerInterface
import com.libui.webview.services.WebViewService
import io.reactivex.rxjava3.disposables.CompositeDisposable
import io.reactivex.rxjava3.kotlin.addTo

class RequestHandler : WebViewHandlerInterface {
    companion object {
        const val id: String = "request"
    }

    private val compositeDisposable = CompositeDisposable()

    override val id: String
        get() {
            return Companion.id
        }

    override fun handle(webView: WebViewEx?, params: Map<String, Any>?) {
        if (webView == null) {
            return
        }

        if (params == null) {
            return
        }

        val uuid: String = params["uuid"] as? String ?: return
        val url: String = params["url"] as? String ?: return

        WebViewService.instance.request(
            params["method"] as? String,
            params["baseUrl"] as? String,
            url,
            cast(params["headers"]),
            cast(params["params"]),
            params["data"],
        )
            .subscribe({ result ->
                runSuccessCallback(webView, uuid, 0, "request:ok", result, params)
            }, { error ->
                runFailCallback(
                    webView,
                    uuid,
                    1,
                    error.localizedMessage ?: "request:fail",
                    null,
                    params
                )
            }).addTo(compositeDisposable)
    }
}